package io.broker.api.client.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.broker.api.client.domain.account.Order;
import io.broker.api.client.domain.account.OrderSide;
import io.broker.api.client.domain.general.BiKiMessage;
import io.broker.api.client.domain.general.CoinAllMessage;
import okhttp3.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class BrokerApiCoinallService {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .pingInterval(10, TimeUnit.SECONDS) // websocket 轮训间隔
            .build();

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public CoinAllMessage newOrder(BigDecimal quantity, BigDecimal price) throws JsonProcessingException {
        Map<String, Object> params = new HashMap<>();
        params.put("side", 1);
        params.put("price", price.toPlainString());
        params.put("size", quantity.toPlainString());
        params.put("systemType", 1);
        params.put("quoteSize", "5");
        params.put("orderType", 0);

        return callRequest(params);
    }

    public CoinAllMessage cancelOrder(Long orderId) throws JsonProcessingException {
        Request request = new Request.Builder()
                .url("https://www.coinall.live/v2/spot/order/cancel?symbol=gt_usdt&orderId=" + orderId + "&t=" + System.currentTimeMillis())
                .delete(null)
                .addHeader("Cookie", "locale=zh_CN; _bl_uid=dvk4k2kqtC152wek8s4Xhzjy3qRL; u_ip=MTExLjE5OS4xODguMTU; isLogin=1; b_id=Njg; b_seokzh_cn=5biB5YWoLGNvaW5hbGws5biB5YWo5Lqk5piT5omALOW4geWFqOS6pOaYk-W5s-WPsCxjb2luYWxs5Lqk5piT5omALGNvaW5hbGzkuqTmmJPlubPlj7Asb2tleCzmr5TnibnluIEsYnRjLOS7peWkquWdiixldGgs6I6x54m55biBLGx0Yyxlb3Msb2tiLGNhYywg5Yqg5a-G6LSn5biBLFhSUCxUUk9OLFN0ZWxsYXIsWExNLFRSWCxiY2gsdXNkdCx1bmRlZmluZWQ; b_seodzh_cn=Q29pbkFsbOaYr-ihjOS4mumihuWFiOeahOaVsOWtl-i1hOS6p-S6pOaYk-W5s-WPsO-8jE9LRXjmt7HluqbmiJjnlaXlkIjkvZzkvJnkvLTjgIJDb2luQWxs5o-Q5L6bQlRD44CBRVRI44CBVVNEVOetieWFqOeQg-S8mOi0qOW4geenje-8jOS4uueUqOaIt-W4puadpeacgOa1geeVheeahOS6pOaYk-S9k-mqjOOAgg; b_seotzh_cn=5pWw5a2X6LSn5biB5Lqk5piT5bmz5Y-w; first_ref=https%3A%2F%2Fwww.coinall.live%2F; u_pid=D6D6lmnvAW5hBGWuBGL7zQ")
                .addHeader("timeout", "10000")
                .addHeader("Origin", "https://www.coinall.live")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("ftID", "521031875360783.011c76343b904e3008fc1ce819187853d3891.1010L8o0.4DAB7112CD12BEE7")
                .addHeader("App-Type", "web")
                .addHeader("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiJvcDAxMDE1NzMzOTk2ODk1NTVDQjA5QkYxRTMxQTNGMzYyT0JMSiIsInVpZCI6IlcrZGhPdnVQdWxac1ZZUm8zMGZmRFE9PSIsInN0YSI6MCwibWlkIjowLCJpYXQiOjE1NzMzOTk2ODksImV4cCI6MTU3NDAwNDQ4OSwiYmlkIjo2OCwiZG9tIjoid3d3LmNvaW5hbGwubGl2ZSIsImlzcyI6Im9rY29pbiIsInN1YiI6IjE5RkYyODE1MTgyQzgwMkIzNEYzMjRGREVGQkQ5OEUzIn0.YwlDPom3RExjaBbtuJzqNfedH7nfzTTZt2WNRaCfg1xpnegmM5lX2v9qnrcXaDmNqGlnuUFFd1Z9T_DEK67wGg")
                .addHeader("devId", "286aa9f1-7531-414f-9741-ff30d5e2e71c")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Accept", "application/json")
                .addHeader("Referer", "https://www.coinall.live/spot/full")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                .addHeader("Connection", "keep-alive")
                .addHeader("cache-control", "no-cache")
                .addHeader("Postman-Token", "00fd365f-dbff-4c22-90b3-a7e627cab755")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseValue = Objects.requireNonNull(response.body()).string();
            System.out.println(responseValue);
            return objectMapper.readValue(responseValue, CoinAllMessage.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private CoinAllMessage callRequest(Map<String, Object> params) throws JsonProcessingException {
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody body = RequestBody.create(mediaType, objectMapper.writeValueAsString(params));
        Request request = new Request.Builder()
                .url("https://www.coinall.live/v2/spot/order/add?symbol=gt_usdt&t=" + System.currentTimeMillis())
                .post(body)
                .addHeader("timeout", "10000")
                .addHeader("Origin", "https://www.coinall.live")
                .addHeader("Accept-Encoding", "deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Authorization", "eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiJvcDAxMDE1NzMzOTk2ODk1NTVDQjA5QkYxRTMxQTNGMzYyT0JMSiIsInVpZCI6IlcrZGhPdnVQdWxac1ZZUm8zMGZmRFE9PSIsInN0YSI6MCwibWlkIjowLCJpYXQiOjE1NzMzOTk2ODksImV4cCI6MTU3NDAwNDQ4OSwiYmlkIjo2OCwiZG9tIjoid3d3LmNvaW5hbGwubGl2ZSIsImlzcyI6Im9rY29pbiIsInN1YiI6IjE5RkYyODE1MTgyQzgwMkIzNEYzMjRGREVGQkQ5OEUzIn0.YwlDPom3RExjaBbtuJzqNfedH7nfzTTZt2WNRaCfg1xpnegmM5lX2v9qnrcXaDmNqGlnuUFFd1Z9T_DEK67wGg")
                .addHeader("devId", "286aa9f1-7531-414f-9741-ff30d5e2e71c")
                .addHeader("Cookie", "locale=zh_CN; _bl_uid=dvk4k2kqtC152wek8s4Xhzjy3qRL; u_ip=MTExLjE5OS4xODguMTU; isLogin=1; b_id=Njg; b_seokzh_cn=5biB5YWoLGNvaW5hbGws5biB5YWo5Lqk5piT5omALOW4geWFqOS6pOaYk-W5s-WPsCxjb2luYWxs5Lqk5piT5omALGNvaW5hbGzkuqTmmJPlubPlj7Asb2tleCzmr5TnibnluIEsYnRjLOS7peWkquWdiixldGgs6I6x54m55biBLGx0Yyxlb3Msb2tiLGNhYywg5Yqg5a-G6LSn5biBLFhSUCxUUk9OLFN0ZWxsYXIsWExNLFRSWCxiY2gsdXNkdCx1bmRlZmluZWQ; b_seodzh_cn=Q29pbkFsbOaYr-ihjOS4mumihuWFiOeahOaVsOWtl-i1hOS6p-S6pOaYk-W5s-WPsO-8jE9LRXjmt7HluqbmiJjnlaXlkIjkvZzkvJnkvLTjgIJDb2luQWxs5o-Q5L6bQlRD44CBRVRI44CBVVNEVOetieWFqOeQg-S8mOi0qOW4geenje-8jOS4uueUqOaIt-W4puadpeacgOa1geeVheeahOS6pOaYk-S9k-mqjOOAgg; b_seotzh_cn=5pWw5a2X6LSn5biB5Lqk5piT5bmz5Y-w; first_ref=https%3A%2F%2Fwww.coinall.live%2F; u_pid=D6D6lmnvAW5hBGWuBGL7zQ")
                .addHeader("Connection", "keep-alive")
                .addHeader("ftID", "521031875360783.011c76343b904e3008fc1ce819187853d3891.1010L8o0.4DAB7112CD12BEE7")
                .addHeader("App-Type", "web")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("Accept", "application/json")
                .addHeader("Referer", "https://www.coinall.live/spot/full")
                .addHeader("cache-control", "no-cache")
                .build();
        try (Response response = client.newCall(request).execute()) {
            String responseValue = Objects.requireNonNull(response.body()).string();
            System.out.println(responseValue);
            return objectMapper.readValue(responseValue, CoinAllMessage.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public List<Order> getOpenOrders() {
//
//        Request request =
//                new Request.Builder()
//                        .url(
//                                "https://www.beex.one/api/order/open_orders?c_token="
//                                        + token
//                                        + "&account_id=454834027336190720&from_order_id=0&limit=50")
//                        .get()
//                        .addHeader("Sec-Fetch-Mode", "cors")
//                        .addHeader("Sec-Fetch-Site", "same-origin")
//                        .addHeader("Origin", "https://www.beex.one")
//                        .addHeader("Accept-Encoding", "deflate, br")
//                        .addHeader("accept-language", "zh-cn")
//                        .addHeader(
//                                "User-Agent",
//                                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36")
//                        .addHeader("content-type", "application/x-www-form-urlencoded")
//                        .addHeader("Accept", "*/*")
//                        .addHeader("Referer", "https://www.beex.one/exchange/665/BEE/USDT")
//                        .addHeader("x-requested-with", "XMLHttpRequest")
//                        .addHeader("Connection", "keep-alive")
//                        .addHeader("cache-control", "no-cache")
//                        .build();
//
//        try (Response response = client.newCall(request).execute()) {
//            String responseValue = Objects.requireNonNull(response.body()).string();
//            Order[] beeOrders = objectMapper.readValue(responseValue, Order[].class);
//
//            return Arrays.asList(beeOrders);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    public static void main(String[] args) {
        BrokerApiCoinallService brokerApiCoinallService = new BrokerApiCoinallService();

        while (true) {
            try {
                CoinAllMessage coinAllMessage = brokerApiCoinallService.newOrder(BigDecimal.valueOf(10), BigDecimal.valueOf(0.5));
                brokerApiCoinallService.cancelOrder(coinAllMessage.getData());
                TimeUnit.SECONDS.sleep(1);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
